<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item prop="usePurpose">
        <el-select
          v-model="queryParams.usePurpose"
          placeholder="请选择借阅目的"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in usePurposeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="beginTime">
        <el-date-picker
          clearable
          size="small"
          style="width: 200px"
          v-model="queryParams.beginTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="endTime">
        <span class="text-margin">至</span>
        <el-date-picker
          clearable
          size="small"
          style="width: 200px"
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:info:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:info:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="infoList"
      @selection-change="handleSelectionChange"
      stripe
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="recNo" />
      <el-table-column
        label="借阅目的"
        align="center"
        prop="usePurpose"
        :formatter="usePurposeFormat"
      />
      <el-table-column label="审批状态" align="center" prop="borrowFlag">
        <template slot-scope="scope">
          <span>{{ scope.row.borrowFlag | borrowStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="顺序号" align="center" prop="orderNo" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="借阅描述" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleVerify(scope.row)"
            v-hasPermi="['system:info:edit']"
            >审批</el-button
          >
          <el-button
            type="text"
            icon="el-icon-edit"
            size="mini"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:info:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:info:remove']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.currentPage"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改借阅管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :before-close="cancel"
    >
      <el-form ref="form" :model="ruleForm" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12" class="margin-form">
            <el-form-item label="申请用户">
              <el-input v-model="userName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借阅目的" prop="usePurpose">
              <el-select
                v-model="ruleForm.usePurpose"
                placeholder="请选择借阅目的"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in usePurposeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" class="margin-form">
            <el-form-item label="借阅人类型" prop="userType">
              <el-select
                v-model="ruleForm.userType"
                placeholder="请选择借阅人类型"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in userTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借阅人姓名" prop="userForeignName">
              <el-input
                v-model="ruleForm.userForeignName"
                placeholder="请输入借阅人名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="ruleForm.userType == 1">
          <el-col :span="12" v-if="ruleForm.userType == 1" class="margin-form">
            <el-form-item label="借阅人证件" prop="userCertificate">
              <el-select
                v-model="ruleForm.userCertificate"
                placeholder="请选择外来借阅人证件"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in borrowerId"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件编号" prop="userCertificateNo">
              <el-input
                v-model="ruleForm.userCertificateNo"
                placeholder="请输入借阅人证件编号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="ruleForm.userType == 1">
          <el-col :span="12" style="width: 98.5%">
            <el-form-item label="借阅人单位" prop="userForeignDept">
              <el-input
                class="unit-form"
                v-model="ruleForm.userForeignDept"
                placeholder="请输入借阅人单位"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" class="margin-form">
            <el-form-item label="开始时间" prop="timeBegin" class="time-picker">
              <el-date-picker
                clearable
                size="medium"
                v-model="ruleForm.timeBegin"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="timeEnd" class="time-picker">
              <el-date-picker
                clearable
                size="medium"
                v-model="ruleForm.timeEnd"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择结束时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item
            label="借阅档案"
            prop="fileTexts"
            @click.native="openSearch"
          >
            <el-input
              class="pointer-change"
              v-model="ruleForm.fileTexts"
              type="textarea"
              placeholder="点击选择借阅档案"
              style="width: 98.5%"
              disabled
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="借阅描述" prop="remark">
            <el-input
              v-model="ruleForm.remark"
              type="textarea"
              placeholder="请输入借阅内容"
              style="width: 98.5%"
            />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(0)">保 存</el-button>
        <el-button type="primary" @click="submitForm(1)">保存并提交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="title"
      :visible.sync="searchOpen"
      width="1500px"
      append-to-body
    >
      <ComplexSearch
        :sortList.sync="sortList"
        :tableLabel.sync="tableLabel"
        :options.sync="options"
        @search="search"
        :headerUpdate="headerUpdate"
        ref="complexRef"
        v-if="dataDestroy"
        :showLogo="false"
      />
      <Drawer
        :drawer.sync="drawerVisible"
        title="已勾选档案："
        :selected.sync="selected"
      />
      <div class="round-btn" @click="openDrawer">
        <el-button type="primary" circle
          >档案 <br />
          借阅</el-button
        >
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSelect">保 存</el-button>
        <el-button @click="cancelTable">取 消</el-button>
      </div>
    </el-dialog>
    <Verify
      :verifyOpen.sync="verifyOpen"
      :verifyRow.sync="verifyRow"
      :usePurposeDict="usePurposeOptions"
      :userTypeDict="userTypeOptions"
      :borrowerIdDict="borrowerId"
    />
  </div>
</template>

<script>
import {
  listInfo,
  updateInfo,
  delInfo,
  addInfo,
  exportInfo,
} from "@/api/fileSharing/fileBorrow/borrowRegister/borrowInfo";
import store from "@/store/index";
import ComplexSearch from "@/views/search/complex/components/Table";
import Drawer from "./components/Drawer";
import Verify from "./components/Verify";
import { search as tableSearch } from "@/api/search/complex";
import { operator } from "@/views/search/complex//components/Table";

export default {
  name: "Info",
  components: {
    ComplexSearch,
    Drawer,
    Verify,
  },
  data() {
    return {
      sortList: [],
      tableLabel: [],
      options: [],
      headerUpdate: false,
      drawerVisible: false,
      selected: [],
      userName: "",
      dataDestroy: true,
      verifyOpen: false,
      verifyRow: {},
      mode: 0,
      selectionOnCancel: [],
      ruleForm: {
        usePurpose: "",
        timeBegin: "",
        timeEnd: "",
        fileTexts: "",
        remark: "",
        userType: "",
        userCertificateNo: "",
        usePurpose: "",
        userForeignName: "",
        userForeignDept: "",
        userCertificate: "",
        userCertificateNo: "",
      },
      borrowerId: [],
      borrowState: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 借阅管理表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      searchOpen: false,
      // 借阅人类型字典
      userTypeOptions: [],
      // 外来借阅人证件字典
      userCertificateOptions: [],
      // 借阅目的字典
      usePurposeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        currentPage: 1,
        usePurpose: null,
        beginTime: null,
        endTime: null,
      },
      dialogPurpose: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        usePurpose: [{ required: true, message: "请选择借阅目的" }],
        fileTexts: [{ required: true, message: "请点击选择借阅档案" }],
        timeBegin: [
          { required: true, message: "请点击选择开始时间", trigger: "change" },
        ],
        timeEnd: [
          { required: true, message: "请点击选择结束时间", trigger: "change" },
        ],
        userType: [{ required: true, message: "请点击选择借阅人类型" }],
        userCertificate: [
          { required: true, message: "请选择借外来借阅人证件类型" },
        ],
        userForeignName: [{ required: true, message: "请输入借阅人名称" }],
        userForeignDept: [{ required: true, message: "请输入外来借阅人名称" }],
        userCertificateNo: [
          { required: true, message: "请输入借阅人证件编号" },
        ],
      },
    };
  },
  created() {
    this.getList(this.queryParams.pageNum, this.queryParams.pageSize);
    this.getDicts("ar_borrow_type").then((response) => {
      this.userTypeOptions = response.data;
    });
    this.getDicts("sys_documents").then((response) => {
      this.userCertificateOptions = response.data;
    });
    this.getDicts("ar_borrow_goal").then((response) => {
      this.usePurposeOptions = response.data;
    });
    this.getDicts("sys_documents").then((res) => {
      this.borrowerId = res.data;
    });
    this.getDicts("ar_borrow_state").then((res) => {
      this.borrowState = res.data;
    });
    const userInfo = store.state.user.fullInfo;
    this.userName = store.getters.nickName;
    this.ruleForm.userName = userInfo.userName;
    this.ruleForm.userNo = userInfo.id;
    this.ruleForm.deptNo = userInfo.dept.deptId;
  },
  methods: {
    cancelTable() {
      // this.selected = [...this.selectedOnCancel];
      this.searchOpen = false;
    },
    saveSelect() {
      this.selectionOnCancel = [...this.selected];
      this.ruleForm.fileTexts = this.selected
        .map((item) => item.jajdh)
        .join("，");

      const arBorrowDetailList = [];
      this.selectionOnCancel = [...this.selected];
      this.selected.forEach((item) => {
        const arBorrowDetail = {};
        arBorrowDetail.sortNo = item.sortNo;
        arBorrowDetail.tableNo = item.recNo;
        arBorrowDetail.processInstNo = item.jajdh;
        arBorrowDetailList.push(arBorrowDetail);
      });
      this.ruleForm.arBorrowDetailList = arBorrowDetailList;
      this.searchOpen = false;
    },
    openDrawer() {
      this.drawerVisible = true;
    },
    search(options = [], keyWords) {
      this.fullscreenLoading = true;
      this.options = options;
      this.keyWords = keyWords;
      const sortMainTableNos = options[0].sortMainTableNo;
      this.$refs.complexRef.activeName = options[0].sortMainTableNo;
      tableSearch(sortMainTableNos, keyWords)
        .then((res) => {
          let tableLabel = res.rows[0];
          tableLabel.forEach((item) => {
            item.label = item.fieldAlias;
            item.prop = item.fieldName;
          });
          tableLabel.push(operator);
          this.tableLabel = tableLabel;
          this.sortList = res.rows[1];
          this.headerUpdate = true;
          this.$refs.complexRef.filterLabels = this.tableLabel;
        })
        .finally(() => (this.fullscreenLoading = false));
    },
    /** 查询借阅管理列表 */
    getList(pageObj) {
      this.loading = true;
      listInfo(pageObj)
        .then((response) => {
          this.infoList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .finally(() => (this.loading = false));
    },
    // 借阅人类型字典翻译
    userTypeFormat(row, column) {
      return this.selectDictLabel(this.userTypeOptions, row.userType);
    },
    // 外来借阅人证件字典翻译
    userCertificateFormat(row, column) {
      return this.selectDictLabel(
        this.userCertificateOptions,
        row.userCertificate
      );
    },
    // 借阅目的字典翻译
    usePurposeFormat(row, column) {
      return this.selectDictLabel(this.usePurposeOptions, row.usePurpose);
    },
    reset() {
      this.headerUpdate = false;
      this.ruleForm = {
        ...this.ruleForm,
        usePurpose: "",
        timeBegin: "",
        timeEnd: "",
        fileTexts: "",
        remark: "",
        userType: "",
        userCertificateNo: "",
        usePurpose: "",
        userForeignName: "",
        userForeignDept: "",
        userCertificate: "",
        userCertificateNo: "",
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.sortList = [];
      this.tableLabel = [];
      this.options = [];
      this.reset();
      this.$refs["form"].resetFields();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectionOnCancel = selection;
      this.ids = selection.map((item) => item.recNo);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.dataDestroy = true;
      this.mode = 0;
      this.title = "新增借阅登记";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.ruleForm = { ...row };
      const fileTexts = row.arBorrowDetailList
        .map((item) => item.processInstNo)
        .toString();
      this.ruleForm.fileTexts = fileTexts;
      this.title = "修改借阅管理";
      this.mode = 1;
      this.open = true;
    },
    /** 提交按钮 */
    submitForm(status) {
      status == 0
        ? (this.ruleForm.approveFlag = 0)
        : (this.ruleForm.approveFlag = 1);
      if (this.ruleForm.timeBegin >= this.ruleForm.timeEnd) {
        this.$message.error("结束时间需大于开始时间");
      } else {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.mode == 0) {
              this.ruleForm.orderNo = this.infoList.length;
              addInfo(this.ruleForm).then((res) => {
                this.getList();
                this.open = false;
                this.$refs["form"].resetFields();
              });
            } else {
              updateInfo(this.ruleForm).then((res) => {
                this.open = false;
                this.$refs["form"].resetFields();
              });
            }
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recNos = row.recNo || this.ids;
      this.$confirm(
        '是否确认删除借阅管理编号为"' + recNos + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delInfo(recNos);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有借阅管理数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportInfo(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    openSearch() {
      this.searchOpen = true;
    },
    handleVerify(row) {
      this.verifyRow = row;
      row.cnName = this.userName;
      this.verifyOpen = true;
    },
  },
  mounted() {
    this.$bus.$on("selected", (data) => {
      this.selected = data;
    });
  },
  beforeDestroy() {
    this.$bus.$off();
  },
  filters: {
    borrowStatus(val) {
      const value = val - 0;
      switch (value) {
        case 0:
          return "待提交";
        case 1:
          return "申请中";
        case 2:
          return "通过";
        case 3:
          return "拒绝";
        case 4:
          return "退回";
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-textarea.is-disabled .el-textarea__inner {
  background-color: transparent;
  color: #606266;
}
::v-deep .el-col-12,
::v-deep .el-form-item .el-form-item--medium,
.time-picker {
  width: 48%;
}
::v-deep .time-picker .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 265px;
}
.round-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  box-sizing: border-box;
  padding: 1px;
  border: 1px solid rgb(145, 145, 145);
  border-radius: 50%;
  background-color: transparent;
  font-size: 14px;
  box-shadow: 0px 0px 5px 1px rgb(145, 145, 145);
  text-align: center;
  cursor: pointer;
}
::v-deep .el-drawer__wrapper {
  position: absolute;
  top: calc(50% - 150px);
}
::v-deep .el-drawer .rtl .drawer {
  width: 100px;
}
::v-deep .drawer {
  height: auto !important;
  height: 300px !important;
  width: auto !important;
}
::v-deep .el-drawer__body {
  padding: 0 20px;
}
::v-deep .el-drawer__body .content {
  height: 180px;

  padding: 10px;
  border: 1px solid rgb(235, 238, 245);
}
::v-deep .el-drawer__body .footer {
  margin-top: 18px;
}
::v-deep .el-form-item__label {
  position: relative;
}
.margin-form {
  margin-right: 20px;
}
::v-deep .el-textarea__inner {
  resize: none;
  height: 150px;
}
::v-deep .pointer-change .el-textarea__inner {
  cursor: pointer;
}
.text-margin {
  margin-right: 10px;
}
</style>
